package com.yycx.starter.rabbitmq.event;

import cn.hutool.core.util.ObjectUtil;
import com.yycx.common.base.utils.FlymeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 监听远程事件,并分发消息到业务模块消息处理器
 *
 * @author zyf
 */
@Component
public class BaseApplicationEvent implements ApplicationListener<YycxRemoteApplicationEvent> {

    @Autowired(required = false)
    Map<String, YycxBusEventHandler> yycxBusEventHandlerMap;

    @Override
    public void onApplicationEvent(YycxRemoteApplicationEvent remoteApplicationEvent) {
        EventObj eventObj = remoteApplicationEvent.getEventObj();
        if (ObjectUtil.isNotEmpty(eventObj)) {
            String handlerName = eventObj.getHandlerName();
            if(FlymeUtils.isNotEmpty(handlerName)){
                YycxBusEventHandler yycxBusEventHandler = yycxBusEventHandlerMap.get(handlerName);
                //获取业务模块消息处理器
                if (FlymeUtils.isNotEmpty(yycxBusEventHandler)) {
                    yycxBusEventHandler.onMessage(eventObj);
                } else {
                    for (YycxBusEventHandler busEventHandler : yycxBusEventHandlerMap.values()) {
                        if (busEventHandler.support(eventObj)) {
                            busEventHandler.onMessage(eventObj);
                        }
                    }
                }
            }
        }
    }

}
